package com.ibm.spatiotemp.server.framework.processor.mysql;

import java.sql.Timestamp;
import java.util.LinkedList;

import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.node.ArrayNode;
import com.ibm.spatiotemp.server.datamodel.gpsdata.TSPoint;
import com.ibm.spatiotemp.server.datamodel.gpsdata.TSPointResultSet;
import com.ibm.spatiotemp.server.datasources.DataSource;
import com.ibm.spatiotemp.server.datasources.mysql.MysqlRawDataAccessor;
import com.ibm.spatiotemp.server.framework.processor.RawDataProcessor;
import com.ibm.spatiotemp.server.framework.request.Request;
import com.ibm.spatiotemp.tools.CoreMessages;
import com.ibm.spatiotemp.tools.STException;

public class MysqlRawDataProcessor extends RawDataProcessor{

	public MysqlRawDataProcessor(DataSource src) {
		super(src);
	}

	@Override
	public TSPointResultSet handleRawDataQuery(Request request) throws Exception {
		return dataaccessor.ScanGPSData(request);
	}

	private LinkedList<TSPoint> getTSPointCollectionFromRequest(Request request) throws Exception
	{
		String modid = request.getId();
		JsonNode dataNode = request.getData();
		if (!dataNode.isArray()) {
			throw new STException(String.format(CoreMessages.STHS0021E, dataNode.toString()));
		}
		ArrayNode dataArray = (ArrayNode)dataNode;
		JsonNode one;
		String t;
		String temp;
		long time;		
		double x;
		double y;
		LinkedList<TSPoint> list = new LinkedList<TSPoint>();
		for (int i=0; i<dataArray.size(); i++) {
			one = dataArray.get(i);
			t = one.get("t").asText();
			if (t == null) {
				throw new STException(String.format(CoreMessages.STHS0001E, "t", t));
			}
			JsonNode pArray = one.get("p").get("coordinates");
			if (pArray.isArray() && pArray.size() == 2) {
				JsonNode xNode = pArray.get(0);
				JsonNode yNode = pArray.get(1);
				if (xNode.isNumber() && yNode.isNumber()) {
					x = xNode.asDouble();
					y = yNode.asDouble();
				} else {
					throw new Exception(String.format(CoreMessages.STHS0001E, "p", pArray));
				}
			} else {
				throw new Exception(String.format(CoreMessages.STHS0001E, "p", pArray));
			}
			temp = t.replaceFirst("T", " ");
			try {
				time = Timestamp.valueOf(temp).getTime();
			} catch (IllegalArgumentException e) {
				throw new Exception(String.format(CoreMessages.STHS0001E, "t", t));
			}
			list.add(new TSPoint(modid,x,y,time));			
		}
		return list;
	}
	
	@Override
	public String handleRawDataInsert(Request request) throws Exception {
		MysqlRawDataAccessor das = (MysqlRawDataAccessor)dataaccessor;
		das.createMovingObjectTable();
		
		String query_string = "";
		LinkedList<TSPoint> list = getTSPointCollectionFromRequest(request);
		
		if (list.size() == 0) {
			return "[0]";
		} else {
			int res = dataaccessor.WriteGPSData(query_string,list);
			return String.format("[%d]", res);
		}
	}
}
